<template>
  <div class="promote-service-key-page">
    <el-card shadow="always">
      <div slot="header" class="clearfix">
        <line-header :title="showTitle"></line-header>
      </div>
      <div class="promote-key-body">
        <div class="key-top-box">
          <div>提示信息：</div>
          <div>
            <span>1、推广提交后后台将在</span>
            <span>1天内完成审核</span>
            <span>，通过后将扣费并发布成功；审核未通过，当次费用将</span>
            <span> 退回余额</span>
            <span>。</span>
          </div>
          <div>
            <span>2、投放时间，最小</span>
            <span>单位为天计算</span>
          </div>
        </div>
        <div class="key-bottom-box">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="120px"
            class="demo-ruleForm"
          >
           <el-form-item required label="链接地址：" prop="address">
              <el-input
                v-model="ruleForm.address"
                placeholder="输入服务页面的地址，例如：https://sem.zhihuo.com"
                :disabled="!isEdit"
              ></el-input>
              <span class="key-sign-text">
                提示：子链接地址为主站点域名的子域名，例如主域名为www.zhihuo.com，子域名seo.zhihuo.com
              </span>
            </el-form-item>
           <el-form-item required label="服务名称：" prop="name">
              <el-input
                v-model="ruleForm.name"
                placeholder=""
                :disabled="!isEdit"
              ></el-input>
            </el-form-item>
           <el-form-item required label="描述信息：" prop="desc">
              <el-input
                v-model="ruleForm.desc"
                placeholder=""
                :disabled="!isEdit"
              ></el-input>
            </el-form-item>
          </el-form>

          <el-form
            :inline="true"
            :model="ruleForm"
            ref="ruleForm"
            label-width="120px"
            class="inline-form-box"
          >
            <div v-for="(item, index) in ruleForm.keys" :key="index">
             <el-form-item required
                label="关键词："
                :prop="'keys.' + index + '.keyName'"
                :rules="{
                  required: true,
                  message: '关键词',
                  trigger: ['blur', 'change']
                }"
              >
                <el-input
                  class="inline-item-box"
                  v-model="item.keyName"
                  placeholder="输入投放关键词"
                  @change="upTotalFee"
                  :disabled="!isEdit"
                ></el-input>
              </el-form-item>
             <el-form-item required label="排名：" label-width="75px">
                <el-select
                  v-model="item.keyRank"
                  placeholder="手动选择排名"
                  class="inline-rank-item-box"
                  :disabled="!isEdit"
                >
                  <el-option v-for="n in 10" :key="n" :label="n" :value="n">
                  </el-option>
                </el-select>
              </el-form-item>
             <el-form-item required label="可用优惠券：" label-width="108px">
                <el-select v-model="item.keyDec" placeholder="可用优惠券" @change="changeSelect" :disabled="!isEdit">
                  <el-option v-for="(item1,index) in quanList" :label="setLabel(item1)" :value="item1.id"></el-option>
                </el-select>
              </el-form-item>

             <el-form-item required label="投放时长：">
                <el-radio-group v-model="item.keyTime" size="medium" @change="upTotalFee" :disabled="!isEdit">
                  <el-radio-button label="30天"></el-radio-button>
                  <el-radio-button label="60天"></el-radio-button>
                  <el-radio-button label="90天"></el-radio-button>
                </el-radio-group>
              </el-form-item>
              <br>
              <el-form-item required label="投放城市：" disabled>

                <el-tag
                  style="margin-right: 6px;"
                  :key="tag"
                  v-for="tag in item.citys"
                  :type="!isEdit?'info':''"
                  :closable="isEdit"
                  :disable-transitions="true"
                  @close="()=>{handleClose(tag,item)}">
                  {{tag}}
                </el-tag>
                <el-cascader
                  placeholder="+ 城市"
                  :disabled="!isEdit || (item.citys&&item.citys.length>=5)"
                  v-model="item.city"
                  :options="options"
                  @change="(value)=>{handleChange(value,item)}">
                </el-cascader>
              </el-form-item>
             <el-form-item required v-if="isEdit">
                <el-button v-if="index == 0" type="text" @click="hkAddNewKey">
                  添加关键词
                </el-button>
                <el-button
                  class="delete-key-btn"
                  v-else
                  type="text"
                  @click="hkClickDeleteKey(item, index)"
                >
                  删除
                </el-button>
              </el-form-item>
            </div>
          </el-form>

          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="120px"
          >
           <el-form-item required label="所需推广费用：" prop="expense">
              <el-input
                v-model="ruleForm.expense"
                placeholder="￥0.00"
                disabled
              ></el-input>
            </el-form-item>
           <el-form-item required label="目前可用余额：" prop="balance" v-if="userInfo.role==2">
              <el-input
                v-model="ruleForm.balance"
                disabled
                placeholder="￥0.00"
              ></el-input>
            </el-form-item>
            <!--审核描述-->
            <el-form-item required  label="审核描述：" v-if="!isEdit">
              <el-input
                required
                type="textarea"
                v-model="ruleForm.mark"
                placeholder="请输入审核描述"
                @change="handleMarkChange"
                :disabled="pro_value.exStatus!=1"
              ></el-input>
            </el-form-item>
           <el-form-item>
              <div class="bottom-button-box">
                <div class="show-status-box" v-if="!isEdit">
                  <!--<span>{{userInfo.role+"   /exStatus"+pro_value.exStatus}}</span>-->
                  <el-button v-if="userInfo.role==2" :type="pro_value.exStatus==3?'success':'danger'" disabled>{{pro_value.status_text}}</el-button>

                  <div v-if="(userInfo.role==1||userInfo.role==3)">
                    <template v-if="pro_value.exStatus==1">
                      <el-button type="primary" @click="hkSetUp(3)" :disabled="(!ruleForm.mark)||ruleForm.mark.length<1">通过</el-button>
                      <el-button type="danger" @click="hkSetUp(2)" :disabled="(!ruleForm.mark)||ruleForm.mark.length<1">不通过</el-button>
                    </template>

                    <template v-else>
                      <el-button  :type="pro_value.exStatus==3?'success':'danger'" disabled>{{pro_value.status_text}}</el-button>
                    </template>

                  </div>
                  <!--<el-button type="danger">已到期</el-button>-->
                  <!--<el-button type="danger">审核未通过</el-button>-->
                </div>

                <!--<el-button type="primary" @click="hkClickSubmit">-->
                <!--再次提交</el-button-->
                <!--&gt;-->

                <!--<el-button type="info" @click="hkClickDisable">禁用</el-button>-->
                <el-button v-else type="primary" @click="hkClickSubmit"
                >提交
                </el-button
                >
                <el-button type="info" plain @click="hkClickCancel"
                >取消
                </el-button
                >
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
  import lineHeader from "@/components/line-header/index";
  import {trace} from "../../utils/trace"
  import {mapGetters} from "vuex"
  import {getCitys, hkGetTimeFmt, Trim} from "../../utils/tools"

  export default {
    components: {lineHeader},
    props: {
      pro_value:Object
    },
    data() {

      return {
        options:[],
        isEdit:true,
        quanList: [],    //券列表
        itemInfo: {
          showType: 1 // 1 新增，2 编辑， 3 查看
        },
        isInputMarkContent:false,
        ruleForm: {
          address: "", //链接地址
          name: "", //服务名称
          desc: "", //描述信息
          expense: "", //推广费用
          balance: "", //目前可用余额
          mark:"",   //审核描述
          keys: [
            {
              keyName: "",
              keyRank: "1",
              keyDec: "",
              keyTime: "30天",
              city:"",
              citys:["武汉","广州"],
            }
          ]
        },
        rules: {
          address: [{message: "请输入活动名称", trigger: ["blur", "change"]}],
          name: [{message: "请选择活动区域", trigger: ["blur", "change"]}],
          desc: [{message: "请选择活动区域", trigger: ["blur", "change"]}],
          expense: [{message: "请选择活动区域", trigger: ["blur", "change"]}],
          balance: [{message: "请选择活动区域", trigger: ["blur", "change"]}],

        }
      };
    },
    watch: {
      pro_value(){
        this.upKeys();
      },
    },
    filters: {},
    computed: {
      showTitle() {
        // console.log(this.itemInfo);
        switch (this.itemInfo.showType) {
          case 1:
            return "新建服务类关键词";
          case 2:
            return "编辑服务类关键词";
          case 3:
            return "查看服务类关键词";
          default:
            break;
        }
      },
      ...mapGetters([
        'config',
        'balance',
        'userInfo',
      ])
    },
    methods: {
      //判断审核描述字符长度并且去除空格
      handleMarkChange(val){

        this.isInputMarkContent = val.trim().length > 0

      },
      init(itemInfo) {
        this.itemInfo = itemInfo;
      },
      onSubmit() {

      },
      //添加关键词
      hkAddNewKey() {
        this.ruleForm.keys.push({
          keyName: "",
          keyRank: "1",
          keyDec: "",
          keyTime: "30天",
          city:"",
          citys:[],
        });
      },
      //删除关键词
      hkClickDeleteKey(item, index) {
        this.ruleForm.keys.splice(index, 1);
      },
      //提交
      hkClickSubmit() {
        // 新建服务推广
        let duration = 1;   //枚举值,单位天 1 30 2 60 3 90 4 180 5 360   单价4毛一天
        let word = "大西瓜";
        let rank = 1;   //1-50
        let address = this.ruleForm.address;    //"https://tracing.glpro.io";
        let name = this.ruleForm.name;    //"西瓜";
        let desc = this.ruleForm.desc;   //"西瓜推广";
        let tt1 =0;
        this.ruleForm.keys.map( async (item, index) => {
          if (item.keyName.length > 0) {
            var cid = null;
            word = item.keyName;
            rank = item.keyRank;
            let cities = item.citys;

            if (item.keyDec != "") cid = item.keyDec;
            duration = parseInt(item.keyTime) / 30;
            trace("hkClickSubmit-新建服务推广-data", {  duration,
              word,
              rank,
              address,
              name,
              desc,
              cid,
              cities})
            let data = await this.$store.dispatch('promote/createLink', {
              duration,
              word,
              rank,
              address,
              name,
              desc,
              cid,
              cities
            })
            trace("hkClickSubmit-新建服务推广-data", data)
            clearTimeout(tt1);
            tt1 = setTimeout(finish,500)
          }
        });

        let finish = ()=>{
          //更新用户数据
          this.$store.dispatch('user/getInfo');
          //回到推广首页 刷新列表
          this.$bus.emit("hiddenKey",1);
        }

      },
      //禁用
      hkClickDisable() {
      },
      //取消
      hkClickCancel() {
        this.$bus.emit("hiddenKey");
      },
      hkSetUp(status) {     //管理员审核服务
        let {id} = this.pro_value;
        let mark = this.ruleForm.mark;
        // let status = 3;   //2 fail ; 3 success
        this.$store.dispatch('promote/seoAudit', {id, mark,status}).then((data) => {
          trace("seoAudit-启用推广-data", data);
          this.$bus.emit("hiddenKey",1);
        })
          .catch((err) => {
            trace("启用广-seoAudit-err", err)
          })
      },
      setLabel(item1) {
        return '￥' + (item1.amount * 0.01).toFixed(2) + " (有效期：" + hkGetTimeFmt(item1.expireTime).slice(5, -3) + ")";
      },
      //计算总的推广费用
      upTotalFee() {
        trace("upTotalFee", this.config.LINK)
        let totalFee = 0;

        this.ruleForm.keys.map(item => {
          trace("item.keyTime=", item.keyTime, parseInt(item.keyTime))
          if (item.keyName.length > 0) {    //填写了关键词 可以提交
            totalFee += this.config.LINK * 0.01 * parseInt(item.keyTime);
          }
        })

        trace("upTotalFee", totalFee)

        this.ruleForm.expense = "￥" + totalFee.toFixed(2);


      },
      // 查询优惠券
      checkQuan() {
        let page = 1;
        let count = 100;
        let direction = 1;    //排序方式
        let kind = 8789324728947;
        let status = 1;

        this.$store.dispatch('finance/couponQuery', {page, count, direction, kind, status}).then((data) => {
          trace("checkQuan-查询优惠券-data", data);
          this.quanList = data.data;
        })
          .catch((err) => {
            trace("查询优惠券-hkClickSubmit-err", err)
          })

      },
      changeSelect(id) {
        this.quanList.map(item => {
          item.disabled = false;
        })
        this.ruleForm.keys.map((item, index) => {
          if (item.keyDec != "") {
            let obj = this.quanList.find((item1) => {
              return item1.id == item.keyDec;
            })
            if (obj) {
              obj.disabled = true;
            }
          }
        })
      },

      upKeys(){
        trace("pro_value=",this.pro_value)
        if(this.pro_value&&this.pro_value.showType==3){
          this.isEdit = false;
          this.ruleForm.address = this.pro_value.address;
          this.ruleForm.name = this.pro_value.name;
          this.ruleForm.desc = this.pro_value.desc;
          this.ruleForm.mark = this.pro_value.mark;
          this.ruleForm.keys = [];
          this.ruleForm.keys.push({
            keyName: this.pro_value.word,
            citys:this.pro_value.cities,
            keyRank: this.pro_value.rank+"",
            keyDec: this.pro_value.cid,
            keyTime: this.pro_value.duration+"天"
          });

          this.upTotalFee();
        }else{
          this.isEdit = true;

          this.ruleForm.address = "";
          this.ruleForm.name = "";
          this.ruleForm.desc = "";
          this.ruleForm.keys = [];
          this.ruleForm.keys.push({
            keyName: "",
            keyRank: "1",
            keyDec: "",
            keyTime: "30天"
          });

          this.upTotalFee();
        }

      },

      handleChange(value,item){
        // trace("handleChange-",value[1],JSON.stringify(item))
        let key = value[1];   //value.slice(value[1].lastIndexOf('/')+1);
        key = Trim(key);
        if(!item.citys){
          item.citys = [];
        }
        let obj = item.citys.find(item=>item==key);
        if(!obj){
          item.citys.push(key);
        }

        this.upItem(item);
        // trace("handleChange-3--",value[1],JSON.stringify(item))
      },
      upItem(item){
       setTimeout(()=>{
         item.city = "+ 城市"
         let item1 = item
         item = {}
         item = item1;
       },25)

        // let item1 = this.ruleForm;
        // this.ruleForm = {};
        // this.ruleForm = item1;
      },
      handleClose(tag,item){
        // trace("change-to =",tag,JSON.stringify(item))
        if(item){
          let id = item.citys.indexOf(tag)
          if(id>=0){
            item.citys.splice(id,1);

          }
        }
        this.upItem(item);
        let item1 = this.ruleForm;
        this.ruleForm = {};
        this.ruleForm = item1;

        // trace("change-to2 =",tag,JSON.stringify(item))
      },

    },
    created() {
      trace("service-created")
      this.options = getCitys()

      // 查询优惠券
      this.checkQuan();

      trace("config=", this.config, this.ruleForm)
      this.ruleForm.expense = "￥0.00";    //+(this.config.LINK*30*0.01).toFixed(2);
      this.ruleForm.balance = "￥" + (this.balance.toFixed(2));

      this.upKeys();
    },
    mounted() {
      trace("service-mounted")

    }
  }
</script>
<style lang="scss" scoped>
  .promote-service-key-page {
    height: 100%;
    padding: 20px 36px 50px 36px;
    background-color: #ecf0f3;

    .header-box {
      display: flex;
      align-items: center;

      .line-box {
        width: 4px;
        height: 19px;
        margin-right: 10px;
        background: #134bdf;
        border-radius: 2px;
      }

      .title-box {
        font-size: 14px;
        font-weight: 500;
        color: #333333;
        line-height: 38px;
      }
    }

    .promote-key-body {
      display: flex;
      flex-direction: column;
      align-items: center;

      .key-top-box {
        padding: 19px 30px;
        text-align: left;
        font-size: 14px;
        font-family: Source Han Sans CN;
        font-weight: 400;
        color: #666666;
        line-height: 30px;
        background: #d5d8da32;
        border-radius: 4px;
      }

      .key-bottom-box {
        margin-top: 40px;
        min-width: 650px;

        .key-sign-text {
          font-size: 12px;
          font-weight: 400;
          color: #c0c4cc;
          line-height: 38px;
        }

        .inline-item-box {
          width: 150px;
        }

        .inline-item-coupon-box,
        .inline-item-rank-box {
          width: 120px;
        }

        .inline-rank-item-box {
          width: 80px;
        }

        .delete-key-btn {
          color: red;
        }

        .bottom-button-box {
          display: flex;
          justify-content: center;

          .show-status-box {
            margin: 0 10px;
          }
        }
      }
    }
  }
</style>
